<template>
  <el-container class="allocation-container">
    <!-- 侧边栏（垂直菜单） -->
    <el-aside class="sidebar">
      <el-menu
        :default-active="activeTab"
        class="menu"
        @select="switchTab"
      >
        <el-menu-item index="reference">查看参考分工</el-menu-item>
        <el-menu-item index="wjx">问卷星</el-menu-item>
        <el-menu-item index="subtask">查看子任务</el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="content">
      <div class="board">
        <!-- 1. 查看参考分工 -->
        <div v-if="activeTab === 'reference'" class="section">
          <h2>查看参考分工</h2>
          <!-- 显示任务详情（此处为示例数据，可根据实际接口调整） -->
          <div class="task-details">
            <h3>任务详情</h3>
            <p><strong>标题：</strong>{{ taskInfo.title }}</p>
            <p><strong>描述：</strong>{{ taskInfo.description }}</p>
            <p><strong>截止时间：</strong>{{ taskInfo.deadline }}</p>
            <p><strong>评分标准：</strong>{{ taskInfo.scoring_criteria }}</p>
            <p><strong>状态：</strong>{{ taskInfo.status }}</p>
          </div>
          <!-- 感兴趣的主题输入 -->
          <div class="theme-input">
            <label>感兴趣的主题：</label>
            <input v-model="theme" type="text" placeholder="请输入感兴趣的主题" />
            <button @click="generatePositions">生成参考职位列表</button>
          </div>
          <!-- 显示参考职位列表 -->
          <div v-if="positions.length" class="result-area">
            <h3>参考职位列表</h3>
            <ul>
              <li v-for="(pos, index) in positions" :key="index">
                <strong>{{ pos.职位 }}</strong> （人数：{{ pos.人数 }}）<br />
                描述：{{ pos.描述 }}
              </li>
            </ul>
          </div>
          <!-- 显示兴趣测试问卷 -->
          <div v-if="survey" class="result-area">
            <h3>兴趣测试问卷</h3>
            <pre>{{ survey }}</pre>
          </div>
        </div>

        <!-- 2. 问卷星 -->
        <div v-if="activeTab === 'wjx'" class="section">
          <h2>问卷星</h2>
          <!-- 跳转到问卷星登录界面的按钮 -->
          <el-button type="primary" @click="goToWjxLogin">跳转到问卷星登录界面</el-button>
          <!-- 输入问卷链接及加载按钮 -->
          <div class="form-group">
            <label>请输入问卷链接：</label>
            <input v-model="wjxLink" type="text" placeholder="例如：https://www.wjx.cn/s/xxxx.html" />
            <el-button type="primary" @click="embedWjxLink">加载问卷</el-button>
          </div>
          <!-- 内嵌问卷链接 -->
          <div v-if="embeddedWjxLink" class="iframe-container">
            <iframe :src="embeddedWjxLink" frameborder="0" class="wjx-iframe"></iframe>
          </div>
        </div>

        <!-- 3. 查看子任务 -->
        <div v-if="activeTab === 'subtask'" class="section">
          <h2>查看子任务</h2>
          <div class="form-group">
            <label>上传填写后的问卷 CSV/Excel 文件：</label>
            <input type="file" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="handleFileUpload" />
          </div>
          <button @click="analyzeResults">分析问卷结果</button>
          <div v-if="analysisResult" class="result-area">
            <h3>成员分工推荐</h3>
            <ul>
              <li v-for="(item, index) in analysisResult" :key="index">
                姓名：{{ item.姓名 }}<br />
                推荐职位：{{ item.推荐职位 }}<br />
                推荐理由：{{ item.推荐理由 }}<br />
                工作内容及时间规划：{{ item.工作内容以及时间规划 }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'TaskAllocation',
  setup() {
    const route = useRoute();
    // 路由参数：taskId, groupId, sysUserId, sysUserName
    const taskId = ref(route.query.taskId || '');
    const groupId = ref(route.query.groupId || '');
    const sysUserId = ref(route.query.UserId || '');
    const sysUserName = ref(route.query.UserName || '');

    // 当前激活的侧边栏选项，默认为“查看参考分工”
    const activeTab = ref('reference');

    const taskInfo = ref({}); // 初始为空

    // 感兴趣的主题输入框内容
    const theme = ref('');

    // 返回的参考职位列表和兴趣调查问卷
    const positions = ref([]);
    const survey = ref('');

    // CSV 文件内容上传后保存的字符串
    const fileContent = ref('');

    // 分工推荐结果
    const analysisResult = ref(null);

    // 内嵌问卷星 URL（请根据实际情况修改）
    const wjxUrl = ref(null);

    // 处理 CSV 文件上传
    const handleFileUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          fileContent.value = e.target.result;
        };
        reader.readAsText(file);
      }
    };

    const wjxLink = ref('');          // 用户输入的问卷链接
    const embeddedWjxLink = ref('');  // 内嵌的问卷链接

    const goToWjxLogin = () => {
      window.open('https://www.wjx.cn/', '_blank');
    };

    const embedWjxLink = () => {
  // 简单验证下链接是否非空，你可以添加更严格的校验
      if (wjxLink.value) {
        embeddedWjxLink.value = wjxLink.value;
      } else {
        alert("请输入有效的问卷链接！");
      }
    };

    // 生成参考职位列表及兴趣调查问卷
    const generatePositions = async () => {
      try {
        const payload = {
          user_id: sysUserId.value,
          task_id: taskId.value,
          group_id: groupId.value,
          theme: theme.value,
        };
        const response = await axios.post("http://39.105.217.183:8000/api/generate-positions/", payload);
        positions.value = response.data.positions;
        survey.value = response.data.survey;
        console.log(response.data);
      } catch (error) {
        console.error('生成参考职位列表失败：', error);
        alert('生成参考职位列表失败，请检查输入信息是否完整！');
      }
    };

    const fetchTaskInfo = async () => {
      try {
        const response = await axios.get(`http://39.105.217.183:8000/api/show_task_detail/${taskId.value}/`, {
          params: { user_id: sysUserId.value }
        });
        if (response.data && response.data.task) {
          taskInfo.value = {
            title: response.data.task.title,
            description: response.data.task.description,
            deadline: response.data.task.deadline,  // 需根据后端返回格式转换为字符串
            scoring_criteria: response.data.task.scoring_criteria,
            status: response.data.task.status,
            students_number: response.data.task.students_number,
          };
        }
      } catch (error) {
        console.error("获取任务详情失败：", error);
      }
    };


    // 分析问卷结果：上传 CSV 文件内容和参考职位列表传给大模型
    const analyzeResults = async () => {
      if (!fileContent.value) {
        alert('请先上传填写后的问卷 CSV 文件！');
        return;
      }
      try {
        const payload = {
          task_id: taskId.value,
          group_id: groupId.value,
          csv_content: fileContent.value,
        };
        const response = await axios.post("http://39.105.217.183:8000/api/allocate-subtasks/", payload);
        analysisResult.value = response.data.analysis;
        console.log(response.data);
      } catch (error) {
        console.error('分析问卷结果失败：', error);
        alert('分析问卷结果失败，请检查输入信息是否完整！');
      }
    };

    // 侧边栏切换
    const switchTab = (val) => {
      activeTab.value = val;
    };

    onMounted(() => {
      console.log("路由参数：", taskId.value, groupId.value, sysUserId.value, sysUserName.value);
      fetchTaskInfo();
    });

    return {
      taskId,
      groupId,
      sysUserId,
      sysUserName,
      activeTab,
      taskInfo,
      theme,
      positions,
      survey,
      fileContent,
      analysisResult,
      wjxUrl,
      generatePositions,
      handleFileUpload,
      analyzeResults,
      switchTab,
      goToWjxLogin,
      embedWjxLink,
      wjxLink,
      embeddedWjxLink,
    }
  }
}
</script>

<style scoped>
.allocation-container {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 220px;
  background-color: #f5f5f5;
  padding: 20px;
  border-right: 1px solid #ebeef5;
}

.menu {
  border-right: none;
}

.content {
  flex: 1;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.board {
  width: 800px;
  background-color: #ffffff;
  padding: 20px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

.btn-group button {
  margin-right: 10px;
  padding: 8px 16px;
}

.side-menu {
  margin: 20px 0;
}

.survey-iframe {
  min-width: 100%;
  min-height: 100px;
  border: none;
}

.input-area, .result-area {
  margin-bottom: 20px;
}

.iframe-container {
  /* 父容器可以设置更大高度，或让其占满可用空间 */
  width: 100%;
  height: 1000px; /* 或其他合适的值 */
  /* 如果需要滚动条，可设置overflow: auto; */
}

.wjx-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

textarea {
  width: 100%;
}

.task-details p {
  margin: 5px 0;
}
</style>